package videoCapture;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class AudioP2P2 implements Runnable{
	public static int PORT = 5555;
	private DatagramSocket dataSocket;
	private DatagramPacket dataPacket;
	private byte receiveByte[];
	private static int BUFSIZE = 1024;

	public AudioP2P2() throws SocketException {
		super();
		dataSocket = new DatagramSocket(PORT);
		receiveByte = new byte[1024];
		dataPacket = new DatagramPacket(receiveByte, receiveByte.length);

	}

	public void start() throws LineUnavailableException, IOException {
		final AudioFormat format = getFormat();
		DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
		final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
		line.available();
		line.open(format,line.getBufferSize());
		line.start();
		byte[] sbuffer;
		while (true) {
			sbuffer = recive();
			if (sbuffer.length > 0){
				try {
					line.write(sbuffer, 0, sbuffer.length);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public byte[] recive() throws IOException {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		// ByteArrayInputStream bin;

		int bufSize = 0;
		int i = 0;
		while (i == 0)// 无数据，则循环
		{
			dataSocket.receive(dataPacket);
			i = dataPacket.getLength();
			bufSize += i;
			// 接收数据
			// System.out.println("server " + i);
			if (i > 0) {
				bout.write(dataPacket.getData(), 0, i);
				i = 0;// 循环接收
				continue;
			}
			break;
		}
//		System.out.println("recive" + bufSize);
		// bin = new ByteArrayInputStream(bout.toByteArray());

		return bout.toByteArray();
	}
	
	

	private AudioFormat getFormat() {
		float sampleRate = 16000;
		int sampleSizeInBits = 8;
		int channels = 1;
		boolean signed = true;
		boolean bigEndian = true;
		return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
				bigEndian);
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			this.start();
		} catch (LineUnavailableException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		AudioP2P2 p2 = new AudioP2P2();
//		p2.start();
		Thread thread = new Thread(p2);
		thread.start();
	}


}
